<?php

namespace catchAdmin\system\controller;

use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\system\model\FieldMapping as FieldMappingModel;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;
use think\Response;

class FieldMapping extends CatchController
{

    protected $fieldMappingModel;

    /**
     *
     * @time 2023/12/13 11:16
     * @param FieldMappingModel $fieldMappingModel
     * @return mixed
     */
    public function __construct(FieldMappingModel $fieldMappingModel)
    {
        $this->fieldMappingModel = $fieldMappingModel;
    }

    /**
     *
     * @time 2023/12/13 11:16
     * @return Response
     */
    public function index(): Response
    {
        return CatchResponse::paginate($this->fieldMappingModel->getList());
    }

    /**
     *
     * @time 2023/12/13 11:16
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $postData = $request->except(["id"]);
        //根据传过来的类型id获取类型名称
        $dicInfo = (new \catchAdmin\system\model\FieldDic())->find($postData["type_id"]);
        if (!empty($dicInfo)) {
            $postData["type_text"] = $dicInfo["name"];
        }
        return CatchResponse::success($this->fieldMappingModel->save($postData));
    }

    /**
     *
     * @time 2023/12/13 11:16
     * @param $id
     * @return Response
     */
    public function read($id): Response
    {
        return CatchResponse::success($this->fieldMappingModel->findBy($id));
    }

    /**
     *
     * @time 2023/12/13 11:16
     * @param $id
     * @param Request $request
     * @return Response
     */
    public function update($id, Request $request): Response
    {
        $postData = $request->post();

        if (isset($postData["type_id"]) && !empty($postData["type_id"])) {
            $dicInfo = (new \catchAdmin\system\model\FieldDic())->find($postData["type_id"]);

            if (!empty($dicInfo)) {
                $postData["type_text"] = $dicInfo["name"];
            }

        }
        return CatchResponse::success($this->fieldMappingModel->updateBy($id, $postData));
    }

    /**
     *
     * @time 2023/12/13 11:16
     * @param $id
     * @return Response
     */
    public function delete($id): Response
    {
        return CatchResponse::success($this->fieldMappingModel->destroy($id));
    }

    public function getFieldMappingByTypeId(Request $request, string $id): \think\response\Json
    {
        if (empty($id)) {
            throw new ValidateException("类型id不能为空");
        }
        $result = $this->fieldMappingModel->where([["type_id", "=", $id]])->select();
        return CatchResponse::success($result);
    }
}